<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      size="small"
    >
      <el-form-item label="企业名称" prop="companyName">
        <el-input
          v-model="queryParams.companyName"
          placeholder="请输入企业名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入手机号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="战区" prop="supervisor">
        <el-select
          v-model="queryParams.supervisor"
          clearable
          placeholder="请选择战区"
          style="width: 200px"
          @change="handleOnChangeDept"
        >
          <el-option
            v-for="(item, index) in searchDept"
            :key="index"
            :label="item.name"
            :value="item.name"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="团队" prop="department">
        <el-select
          v-model="queryParams.department"
          clearable
          placeholder="请选择团队"
          style="width: 200px"
        >
          <el-option
            v-for="(item, index) in teamList"
            :key="index"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="销售" prop="salesman">
        <el-input
          v-model="queryParams.salesman"
          placeholder="请输入销售"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="进件人" prop="purchasePerson">
        <el-input
          v-model="queryParams.purchasePerson"
          placeholder="请输入进件人"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="授信额度">
        <el-input-number
          v-model="queryParams.loanProductStart"
          :controls="false"
          step-strictly
          :step="0.01"
          :precision="2"
          :min="0"
          style="width: 76px"
        />
        <span class="ml10 mr10">-</span>
        <el-input-number
          v-model="queryParams.loanProductEnd"
          :controls="false"
          step-strictly
          :min="0"
          :step="0.01"
          :precision="2"
          style="width: 76px"
        />
        <span class="ml10">万</span>
      </el-form-item>
      <el-form-item label="放款额度">
        <el-input-number
          v-model="queryParams.creditLimitStart"
          :controls="false"
          step-strictly
          :min="0"
          :step="0.01"
          :precision="2"
          style="width: 76px"
        />
        <span class="ml10 mr10">-</span>
        <el-input-number
          v-model="queryParams.creditLimitEnd"
          :controls="false"
          step-strictly
          :min="0"
          :step="0.01"
          :precision="2"
          style="width: 76px"
        />
        <span class="ml10">万</span>
      </el-form-item>
      <el-form-item label="客户自有额度">
        <el-input-number
          v-model="queryParams.ownQuotaStart"
          :controls="false"
          step-strictly
          :min="0"
          :step="0.01"
          :precision="2"
          style="width: 76px"
        />
        <span class="ml10 mr10">-</span>
        <el-input-number
          v-model="queryParams.ownQuotaEnd"
          :controls="false"
          step-strictly
          :min="0"
          :step="0.01"
          :precision="2"
          style="width: 76px"
        />
        <span class="ml10">万</span>
      </el-form-item>
      <el-form-item label="客户资金需求量">
        <el-input-number
          v-model="queryParams.requiredFundsStart"
          :controls="false"
          step-strictly
          :min="0"
          :step="0.01"
          :precision="2"
          style="width: 76px"
        />
        <span class="ml10 mr10">-</span>
        <el-input-number
          v-model="queryParams.requiredFundsEnd"
          :controls="false"
          step-strictly
          :min="0"
          :step="0.01"
          :precision="2"
          style="width: 76px"
        />
        <span class="ml10">万</span>
      </el-form-item>
      <el-form-item label="是否算进件" prop="effectivePurchase">
        <el-select
          v-model="queryParams.effectivePurchase"
          clearable
          style="width: 80px"
        >
          <el-option label="是" value="1" />
          <el-option label="否" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="进件日期" prop="purchaseDate" style="width: 270px">
        <el-date-picker
          v-model="dateRange"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="handleDateValue"
          size="small"
        />
        <!-- <el-date-picker
          v-model="queryParams.purchaseDateStart"
          type="date"
          placeholder="开始日期"
          value-format="YYYY-MM-DD"
          style="width: 120px"
          clearable
        />
        <span class="ml10 mr10">-</span>
        <el-date-picker
          v-model="queryParams.purchaseDateEnd"
          type="date"
          placeholder="结束日期"
          value-format="YYYY-MM-DD"
          style="width: 120px"
          clearable
        /> -->
      </el-form-item>
      <el-form-item label="进件时间" prop="type">
        <el-radio-group v-model="queryParams.type" size="small">
          <el-radio label="">全部</el-radio>
          <el-radio label="3">今日</el-radio>
          <el-radio label="0">0-3个月</el-radio>
          <el-radio label="1">3-6个月</el-radio>
          <el-radio label="2">6个月以上</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        label="客服部门"
        prop="customerId"
        v-hasRole="['ITServer', 'manager']"
      >
        <el-select
          v-model="queryParams.customerId"
          clearable
          placeholder="请选择客服部门"
          style="width: 200px"
          @change="handleOnChangeCustomer"
        >
          <el-option
            v-for="(item, index) in searchKeFuDept"
            :key="index"
            :label="item.deptName"
            :value="item.deptId"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label="进件人"
        prop="userId"
        v-hasRole="['ITServer', 'manager', 'CustomerServiceDirector']"
      >
        <el-select
          v-model="queryParams.userId"
          clearable
          placeholder="请选择进件人"
          style="width: 200px"
        >
          <el-option
            v-for="item in purchaseOptions"
            :key="item.id"
            :label="item.nickName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">
          搜索
        </el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          size="small"
          @click="handleAdd"
        >
          新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          size="small"
          :disabled="multiple"
          @click="handleDelete"
        >
          删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          size="small"
          icon="Download"
          @click="handleExport"
          v-hasPermi="['monitor:operlog:export']"
        >
          导出
        </el-button>
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        :columns="columns"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="list"
      size="small"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />

      <el-table-column
        label="企业名称"
        align="center"
        prop="companyName"
        width="200"
        fixed="left"
        show-overflow-tooltip
      />
      <el-table-column
        label="手机号码"
        align="center"
        fixed="left"
        prop="phone"
        width="120"
      />
      <el-table-column
        label="进件人"
        align="center"
        prop="purchasePerson"
        width="100"
        v-if="handleShow('进件人', chooseList)"
      />
      <el-table-column
        label="进件日期"
        align="center"
        prop="purchaseDate"
        width="150"
        v-if="handleShow('进件日期', chooseList)"
      />
      <el-table-column
        v-if="handleShow('法人', chooseList)"
        label="法人"
        align="center"
        prop="leName"
        width="100"
      />
      <el-table-column
        label="战区"
        align="center"
        prop="supervisor"
        width="100"
        v-if="handleShow('战区', chooseList)"
      />
      <el-table-column
        v-if="handleShow('团队', chooseList)"
        label="团队"
        align="center"
        prop="department"
        width="100"
      />
      <el-table-column
        v-if="handleShow('销售', chooseList)"
        label="销售"
        align="center"
        prop="salesman"
        width="100"
      />
      <el-table-column
        v-if="handleShow('省份', chooseList)"
        label="省份"
        align="center"
        prop="province"
        width="100"
      />
      <el-table-column
        v-if="handleShow('城市', chooseList)"
        label="城市"
        align="center"
        prop="city"
        width="100"
      />
      <el-table-column
        v-if="handleShow('身份证', chooseList)"
        label="身份证"
        align="center"
        prop="idCards"
        width="170"
      />

      <el-table-column
        v-if="handleShow('上次进件时间', chooseList)"
        label="上次进件时间"
        align="center"
        prop="lastPurchaseDate"
        width="150"
      />
      <el-table-column
        v-if="handleShow('进件间隔（月）', chooseList)"
        label="进件间隔（月）"
        align="center"
        prop="purchaseInterval"
        width="120"
      />
      <el-table-column
        v-if="handleShow('是否公司内部', chooseList)"
        label="是否公司内部"
        align="center"
        :formatter="formatter('internal')"
        width="120"
      />
      <el-table-column
        v-if="handleShow('授信额度', chooseList)"
        label="授信额度"
        align="center"
        width="100"
        :formatter="parseAmount('loanProduct')"
      />
      <el-table-column
        v-if="handleShow('放款额度', chooseList)"
        label="放款额度"
        align="center"
        width="100"
        :formatter="parseAmount('creditLimit')"
      />
      <el-table-column
        v-if="handleShow('出额产品', chooseList)"
        label="出额产品"
        align="center"
        width="100"
        prop="loanAmount"
      />
      <el-table-column
        v-if="handleShow('申请渠道', chooseList)"
        label="申请渠道"
        align="center"
        prop="channel"
        width="100"
      />
      <el-table-column
        v-if="handleShow('前年开票金额', chooseList)"
        label="前年开票金额"
        align="center"
        width="120"
        :formatter="parseAmount('beforeAmount')"
      />
      <el-table-column
        v-if="handleShow('去年开票金额', chooseList)"
        label="去年开票金额"
        align="center"
        width="120"
        :formatter="parseAmount('lastAmount')"
      />
      <el-table-column
        v-if="handleShow('今年开票金额', chooseList)"
        label="今年开票金额"
        align="center"
        width="120"
        :formatter="parseAmount('currentAmount')"
      />
      <el-table-column
        v-if="handleShow('是否算进件', chooseList)"
        label="是否算进件"
        align="center"
        :formatter="formatter('effectivePurchase')"
        width="100"
      />
      <el-table-column
        v-if="handleShow('不算进件的原因', chooseList)"
        label="不算进件的原因"
        align="center"
        prop="uneffectiveReason"
        show-overflow-tooltip
        width="130"
      />
      <el-table-column
        v-if="handleShow('备注', chooseList)"
        label="备注"
        align="center"
        prop="remarks"
        show-overflow-tooltip
        width="130"
      />
      <el-table-column
        v-if="handleShow('客户自有额度', chooseList)"
        label="客户自有额度"
        align="center"
        prop="ownQuota"
        show-overflow-tooltip
        width="130"
      />
      <el-table-column
        v-if="handleShow('客户资金需求量', chooseList)"
        label="客户资金需求量"
        align="center"
        prop="requiredFunds"
        show-overflow-tooltip
        width="130"
      />
      <!-- /v-if="hasAdmin" -->
      <el-table-column
        v-if="handleShow('批次名称', chooseList)"
        label="批次名称"
        v-hasRole="['ITServer', 'admin', 'manager', 'admin2']"
        align="center"
        prop="batchName"
        show-overflow-tooltip
        width="130"
      />

      <el-table-column
        label="操作"
        width="180"
        align="center"
        class-name="small-padding fixed-width"
        fixed="right"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
          >
            修改
          </el-button>
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改进件企业对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="110px"
        size="small"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="进件日期" prop="purchaseDate">
              <el-date-picker
                v-model="form.purchaseDate"
                type="date"
                placeholder="请选择进件日期"
                style="width: 100%"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="战区" prop="supervisor">
              <el-select
                v-model="form.supervisor"
                clearable
                placeholder="请选择战区"
                style="width: 100%"
                @change="handleOnChangeDept"
              >
                <el-option
                  v-for="(item, index) in searchDept"
                  :key="index"
                  :label="item.name"
                  :value="item.name"
                />
              </el-select>
              <!-- <el-input v-model="form.supervisor" placeholder="请输入战区" /> -->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="团队" prop="department">
              <el-select
                v-model="form.department"
                clearable
                style="width: 100%"
                placeholder="请选择团队"
              >
                <el-option
                  v-for="(item, index) in teamList"
                  :key="index"
                  :label="item"
                  :value="item"
                />
              </el-select>
              <!-- <el-input v-model="form.department" placeholder="请输入团队" /> -->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="销售" prop="salesman">
              <el-input v-model="form.salesman" placeholder="请输入销售" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="进件人" prop="purchasePerson">
              <el-input
                v-model="form.purchasePerson"
                placeholder="请输入进件人"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="企业名称" prop="companyName">
              <el-input v-model="form.companyName" placeholder="请输入企业名称">
                <template #append>
                  <el-button
                    @click="getCompanyDetail(form.companyName)"
                    :icon="Search"
                  />
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="省" prop="province">
              <el-select
                v-model="form.province"
                placeholder="请选择省"
                filterable
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="item in provinces"
                  :key="item.name"
                  :label="item.name"
                  :value="item.name"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="市" prop="city">
              <el-input v-model="form.city" placeholder="请输入市" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="法人" prop="leName">
              <el-input v-model="form.leName" placeholder="请输入法人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证" prop="idCards">
              <el-input v-model="form.idCards" placeholder="请输入身份证" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入手机号码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码2" prop="phoneBak">
              <el-input v-model="form.phoneBak" placeholder="请输入手机号码2" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否算进件" prop="effectivePurchase">
              <el-radio-group v-model="form.effectivePurchase">
                <el-radio label="1">是</el-radio>
                <el-radio label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col v-if="form.effectivePurchase === '0'" :span="24">
            <el-form-item label="不算进件的原因" prop="uneffectiveReason">
              <el-input
                v-model="form.uneffectiveReason"
                type="textarea"
                :rows="4"
                placeholder="请输入不算进件的原因"
                maxlength="200"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上次进件时间" prop="lastPurchaseDate">
              <el-date-picker
                v-model="form.lastPurchaseDate"
                type="date"
                placeholder="请选择上次进件时间"
                style="width: 100%"
                value-format="YYYY-MM-DD"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="进件间隔" prop="purchaseInterval">
              <el-input
                v-model.number="form.purchaseInterval"
                placeholder="请输入进件间隔"
              >
                <template #append>月</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否公司内部" prop="internal">
              <el-switch
                v-model="form.internal"
                inline-prompt
                active-text="是"
                active-value="1"
                inactive-text="否"
                inactive-value="0"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出额产品" prop="loanAmount">
              <el-input
                v-model="form.loanAmount"
                placeholder="请输入出额产品"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="授信额度" prop="loanProduct">
              <el-input
                v-model="form.loanProduct"
                placeholder="请输入授信额度"
                @input="toNumber($event, 'loanProduct')"
              >
                <template #append>万</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="放款额度" prop="creditLimit">
              <el-input
                v-model="form.creditLimit"
                placeholder="请输入放款额度"
                @input="toNumber($event, 'creditLimit')"
              >
                <template #append>万</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="渠道" prop="channel">
              <el-input v-model="form.channel" placeholder="请输入渠道" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="客户自有额度" prop="ownQuota">
              <el-input
                v-model="form.ownQuota"
                placeholder="请输入客户自有额度"
                @input="toNumber($event, 'ownQuota')"
              >
                <template #append>万</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户资金需求量" prop="requiredFunds">
              <el-input
                v-model="form.requiredFunds"
                placeholder="请输入放款额度"
                @input="toNumber($event, 'requiredFunds')"
              >
                <template #append>万</template>
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item
              :label="`${
                Number(dayjs(form.purchaseDate).format('YYYY')) - 2
              }年开票金额`"
              prop="beforeAmount"
            >
              <el-input
                v-model="form.beforeAmount"
                :placeholder="`请输入${
                  Number(dayjs(form.purchaseDate).format('YYYY')) - 2
                }年开票金额`"
                @input="toNumber($event, 'beforeAmount')"
              >
                <template #append>万</template>
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item
              :label="`${
                Number(dayjs(form.purchaseDate).format('YYYY')) - 1
              }年开票金额`"
              prop="lastAmount"
            >
              <el-input
                v-model="form.lastAmount"
                :placeholder="`请输入${
                  Number(dayjs(form.purchaseDate).format('YYYY')) - 1
                }年开票金额`"
                @input="toNumber($event, 'lastAmount')"
              >
                <template #append>万</template>
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item
              :label="`${Number(
                dayjs(form.purchaseDate).format('YYYY')
              )}年开票金额`"
              prop="currentAmount"
            >
              <el-input
                v-model="form.currentAmount"
                :placeholder="`请输入${Number(
                  dayjs(form.purchaseDate).format('YYYY')
                )}年开票金额`"
                @input="toNumber($event, 'currentAmount')"
              >
                <template #append>万</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <!-- remarks 备注 -->
            <el-form-item label="备注" prop="remarks">
              <el-input
                v-model="form.remarks"
                type="textarea"
                :rows="4"
                placeholder="请输入备注"
                maxlength="200"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>
        <div style="text-align: 'right'">
          <el-button
            style="margin-left: '10px'"
            size="small"
            type="primary"
            icon="Plus"
            @click="addPurchase"
          >
            添加出额产品
          </el-button>
        </div>
        <el-row
          v-for="(item, index) in form.purchaseProductDetails"
          :key="index"
        >
          <el-col :span="7">
            <el-form-item :label="`进件产品${index + 1}`" prop="province">
              <el-select
                v-model="item.productId"
                filterable
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="lo in loanList"
                  :key="lo.id"
                  :label="lo.productName"
                  :value="lo.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="出额（万）" prop="expenditureAmount">
              <el-input
                v-model="item.expenditureAmount"
                @change="expenditureOnChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="放款（万）" prop="productAmount">
              <el-input
                v-model="item.productAmount"
                @change="productOnChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="3" style="text-align: center">
            <el-icon @click="handleDialogDelete(index)"><Delete /></el-icon>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 列展示 -->
    <el-dialog
      v-model="dialogVisible"
      align-center
      title="展示列"
      width="600px"
      :before-close="handleColumnsClose"
    >
      <div class="chooseTag">
        <div
          class="chooseTagItem"
          v-for="(item, index) in chooseList"
          :key="index"
        >
          <el-checkbox
            v-model="item.checked"
            :label="item.label"
            @change="handleCheck(item.label, item.checked)"
          />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import * as api from '@/api/company/incoming'
import { computed, ref } from 'vue'
import { getUserProfile } from '@/api/system/user'
import { dayjs } from 'element-plus'
import { Search, Delete } from '@element-plus/icons-vue'

import { listDept } from '@/api/system/dept'
import { getSearchDeptAll } from '@/api/system/config'
import { getLoanListNotPage, getPurchaseList } from '@/api/product'
import useUserStore from '@/store/modules/user'

const { proxy } = getCurrentInstance()

const { roles } = useUserStore()

const list = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref('')
const provinces = proxy.getProvinces().filter((item) => item.ProID !== -1)

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    customerId: undefined,
    companyName: undefined,
    phone: undefined,
    supervisor: undefined,
    department: undefined,
    salesman: undefined,
    purchasePerson: undefined,
    loanProductStart: undefined,
    loanProductEnd: undefined,
    creditLimitStart: undefined,
    creditLimitEnd: undefined,
    purchaseDateStart: undefined,
    purchaseDateEnd: undefined,
    ownQuotaStart: undefined,
    ownQuotaEnd: undefined,
    requiredFundsStart: undefined,
    requiredFundsEnd: undefined,
    userId: undefined,
    type: '3',
  },
  rules: {
    companyName: [
      { required: true, message: '进件企业名称不能为空', trigger: 'blur' },
    ],
    purchasePerson: [
      { required: true, message: '进件人不能为空', trigger: 'blur' },
    ],
    phone: [{ min: 11, max: 11, message: '手机号为11位', trigger: 'blur' }],
    phoneBak: [{ min: 11, max: 11, message: '手机号为11位', trigger: 'blur' }],
    effectivePurchase: [
      { required: true, message: '请选择是否算进件', trigger: 'change' },
    ],
  },
})

const hasAdmin = computed(() => {
  return roles.some((element) =>
    ['ITServer', 'admin', 'manager', 'admin2'].includes(element)
  )
})

const hasIT = computed(() => {
  return roles.some((element) => ['ITServer', 'manager'].includes(element))
})

const hasCustomer = computed(() => {
  return roles.some((element) =>
    ['ITServer', 'manager', 'CustomerServiceDirector'].includes(element)
  )
})

const { queryParams, form, rules } = toRefs(data)

const dateRange = ref([])
const handleDateValue = (val) => {
  queryParams.value.purchaseDateStart = val?.[0] ?? ''
  queryParams.value.purchaseDateEnd = val?.[1] ?? ''
}

function expenditureOnChange(e) {
  form.value.loanProduct = form.value.purchaseProductDetails
    .map((item) => {
      return Number(item.expenditureAmount)
    })
    .filter((value) => {
      return !isNaN(value)
    })
    .reduce((total, current) => total + current, 0)
    .toFixed(2)
}
function productOnChange(e) {
  form.value.creditLimit = form.value.purchaseProductDetails
    .map((item) => {
      return Number(item.productAmount)
    })
    .filter((value) => {
      return !isNaN(value)
    })
    .reduce((total, current) => total + current, 0)
    .toFixed(2)
}

function formatter(field) {
  return (row) => (row[field] === '1' ? '是' : '否')
}

function parseAmount(field) {
  return (row) => {
    let s = ''
    if (!row[field]) return ''
    switch (field) {
      case 'beforeAmount':
        s = `${Number(dayjs(row['purchaseDate']).format('YYYY')) - 2}年-${
          row[field]
        }万`
        break
      case 'lastAmount':
        s = `${dayjs(row['purchaseDate']).format('YYYY') - 1}年-${row[field]}万`
        break
      case 'currentAmount':
        s = `${dayjs(row['purchaseDate']).format('YYYY')}年-${row[field]}万`
        break
      default:
        s = `${row[field]}万`
        break
    }

    return s
  }
}

function toNumber(value, field) {
  const s = value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1')
  if (s !== value) {
    form.value[field] = s
  }
}

/** 查询进件企业列表 */
function getList() {
  loading.value = true
  api.query(queryParams.value).then((response) => {
    list.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

/** 取消按钮 */
function cancel() {
  open.value = false
  reset()
}

/** 表单重置 */
function reset() {
  form.value = {
    id: undefined,
    purchaseDate: undefined,
    supervisor: undefined,
    department: undefined,
    salesman: undefined,
    province: undefined,
    city: undefined,
    purchasePerson: undefined,
    companyName: undefined,
    leName: undefined,
    idCards: undefined,
    phone: undefined,
    phoneBak: undefined,
    lastPurchaseDate: undefined,
    purchaseInterval: undefined,
    internal: undefined,
    loanProduct: undefined,
    creditLimit: undefined,
    loanAmount: undefined,
    ownQuota: undefined,
    requiredFunds: undefined,
    channel: undefined,
    beforeAmount: undefined,
    lastAmount: undefined,
    currentAmount: undefined,
    effectivePurchase: undefined,
    uneffectiveReason: undefined,
    remarks: undefined,
    purchaseProductDetails: [],
    ownQuota: undefined,
    requiredFunds: undefined,
  }
  proxy.resetForm('formRef')
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryRef')
  dateRange.value = []

  queryParams.value.purchaseDateStart = undefined
  queryParams.value.purchaseDateEnd = undefined
  queryParams.value.creditLimitStart = undefined
  queryParams.value.creditLimitEnd = undefined
  queryParams.value.loanProductStart = undefined
  queryParams.value.loanProductEnd = undefined
  handleQuery()
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  form.value = {
    ...form.value,
    ...{
      purchasePerson: user.value.nickName,
      purchaseDate: dayjs(new Date()).format('YYYY-MM-DD'),
    },
  }
  title.value = '添加进件企业'
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  form.value = { ...row }
  open.value = true
  title.value = '修改进件企业'
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs['formRef'].validate((valid) => {
    if (valid) {
      if (form.value.id !== undefined) {
        api.update(form.value).then((response) => {
          proxy.$modal.msgSuccess('修改成功')
          open.value = false
          getList()
        })
      } else {
        api.add(form.value).then((response) => {
          proxy.$modal.msgSuccess('新增成功')
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const id = row.id ? [row.id] : ids.value
  proxy.$modal
    .confirm('是否确认删除进件企业编号为"' + id + '"的数据项？')
    .then(function () {
      const idsString = id.map((item) => item.toString())
      return api.remove(idsString)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}

const user = ref()
function getUser() {
  getUserProfile().then((response) => {
    user.value = response.data
    // this.roleGroup = response.roleGroup;
    // this.postGroup = response.postGroup;
  })
}

// 获取公司信息
const companyInfo = ref()
function getCompanyDetail(name) {
  api
    .getCompanyInfo({
      companyName: name,
    })
    .then((res) => {
      form.value = {
        ...form.value,
        ...{
          province: res.data.province,
          city: res.data.city,
          leName: res.data.legalPerson,
        },
      }
    })
}

const searchDept = ref([])
const teamList = ref([])
function handleOnChangeDept(item) {
  queryParams.value.department = ''
  teamList.value = searchDept.value.filter((o) => o.name === item)[0].list
}

function getSearchDeptList() {
  getSearchDeptAll().then((res) => {
    searchDept.value = res.data.map((o) => {
      return { name: o.parentDeptName, list: o.deptNames?.split(',') }
    })
  })
}

const searchKeFuDept = ref([])

function getKeFuDept() {
  listDept({ deptName: '客服' }).then((res) => {
    searchKeFuDept.value = res.data
  })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    '/purchase-company/export',
    {
      ...queryParams.value,
    },
    `config_${new Date().getTime()}.xlsx`
  )
}

const arr = localStorage.getItem('incomingSearchList')

const columns = ref(
  arr
    ? JSON.parse(arr)
    : [
        { key: 2, label: `进件人`, checked: true },
        { key: 3, label: `进见日期`, checked: true },
        { key: 4, label: `法人`, checked: true },
        { key: 5, label: `战区`, checked: true },
        { key: 6, label: `团队`, checked: true },
        { key: 7, label: `销售`, checked: true },
        { key: 8, label: `省份`, checked: true },
        { key: 9, label: `城市`, checked: true },
        { key: 10, label: `身份证`, checked: true },
        { key: 11, label: `上次进件时间`, checked: true },
        { key: 12, label: `进件间隔（月）`, checked: true },
        { key: 13, label: `是否公司内部`, checked: true },
        { key: 14, label: `授信额度`, checked: true },
        { key: 15, label: `放款额度`, checked: true },
        { key: 16, label: `出额产品`, checked: true },
        { key: 17, label: `申请渠道`, checked: true },
        { key: 18, label: `前年开票金额`, checked: true },
        { key: 19, label: `去年开票金额`, checked: true },
        { key: 20, label: `今年开票金额`, checked: true },
        { key: 21, label: `是否算进件`, checked: true },
        { key: 22, label: `不算进件的原因`, checked: true },
        { key: 23, label: `备注`, checked: true },
        { key: 24, label: `客户自有额度`, checked: true },
        { key: 25, label: `客户资金需求量`, checked: true },
        { key: 26, label: `批次名称`, checked: true },
      ]
)

const loanList = ref([])
function getLoanList() {
  getLoanListNotPage().then((res) => {
    loanList.value = res.data
  })
}

function addPurchase() {
  if (form.value.purchaseProductDetails === null) {
    form.value.purchaseProductDetails = [] // 如果为null，则赋值为空数组
  }

  if (form.value.purchaseProductDetails.length == 0) {
    form.value.purchaseProductDetails = [
      {
        id: null,
        productId: null,
        productAmount: null,
      },
    ]
  } else {
    form.value.purchaseProductDetails.push({
      id: null,
      productId: null,
      productAmount: null,
    })
  }
}

function handleDialogDelete(index) {
  form.value.purchaseProductDetails?.splice(index, 1)
}

const purchaseOptions = ref([])
function getPurchaseOptions() {
  getPurchaseList({
    customerId: queryParams.value.customerId,
  }).then((res) => {
    purchaseOptions.value = res.rows
  })
}

function handleOnChangeCustomer() {
  getPurchaseOptions()
}

getList()
if (roles.some((element) => ['ITServer', 'manager'].includes(element))) {
  console.log('hasIT', hasIT)
  getKeFuDept()
}
if (
  roles.some((element) =>
    ['ITServer', 'manager', 'CustomerServiceDirector'].includes(element)
  )
) {
  console.log('hasCustomer', hasCustomer)
  getPurchaseOptions()
}

// 勾选框：table 列是否展示
const chooseList = ref(columns)
// 列展示
const dialogVisible = ref(false)
const handleColumnsShow = () => {
  dialogVisible.value = true
}
const handleColumnsClose = () => {
  dialogVisible.value = false
}
// 多选框
const handleCheck = (val, status) => {
  chooseList.value = chooseList.value.reduce((list, item) => {
    if (val === item.name) {
      item.checked = status
    }
    list.push(item)
    return list
  }, [])
  localStorage.setItem('incomingSearchList', JSON.stringify(chooseList.value))
}

const handleShow = (val, list) => {
  const result = list && list.find((item) => item.label === val)
  return result?.checked
}

// 2、table 表头：是否有缓存
const result = JSON.parse(localStorage.getItem('incomingSearchList'))
chooseList.value =
  (result && Object.keys(result).length === 0) || result === null
    ? columns.value
    : result
getUser()

getLoanList()
getSearchDeptList()
</script>

<style lang="less" scoped>
::v-deep(.el-input-number .el-input__inner) {
  text-align: left;
}
</style>
